"""
酒店管理系统 MCP 服务器 - 简化版
使用 FastMCP 构建，更简洁且符合 MCP 标准
"""

import logging
from typing import List, Optional, Dict, Any
from datetime import date

#from fastmcp import FastMCP
from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field

from configs.basic_config import DB_TYPE, DB_HOST, DB_PASSWORD, DB_PATH, DB_USER, DB_NAME
from db.database_manager import DatabaseManager
from sql.init_db import initialize_database
from tools.sqllite.hotel_tool import HotelManagementTools, HotelSearchParams
from tools.sqllite.booking_system_tool import BookingSystemTools, BookingParams, CancellationParams

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

try:
    #from mcp.server.fastmcp import FastMCP

    # 创建 FastMCP 实例 - 这是唯一的服务器实例
    #mcp = FastMCP("酒店管理 MCP 服务器")
    mcp = FastMCP("酒店管理 MCP 服务器", host='0.0.0.0', port=9000, stateless_http=True)
except ImportError:
    logger.error("❌ 无法导入 mcp，请安装: pip install mcp")
    raise

# 全局工具实例
hotel_tools: Optional[HotelManagementTools] = None
booking_tools: Optional[BookingSystemTools] = None

logger.info("🚀 初始化酒店管理 MCP 服务器...")

# 初始化数据库
try:
    if DB_TYPE == "mysql":
        db_manager = DatabaseManager(
            db_type=DB_TYPE,
            host=DB_HOST,
            user=DB_USER,
            password=DB_PASSWORD,
            database=DB_NAME
        )
    else:
        db_manager = DatabaseManager(
            db_type=DB_TYPE,
            database=DB_PATH
        )

    logger.info("💾 正在初始化数据库...")
    initialize_database(db_manager)
    logger.info("✅ 数据库初始化成功.")

    # 初始化工具实例
    logger.info("🛠️ 正在初始化工具实例...")
    hotel_tools = HotelManagementTools(db_manager)
    booking_tools = BookingSystemTools(db_manager)
    logger.info("✅ 工具实例初始化成功.")

except Exception as e:
    logger.error(f"❌ 初始化失败: {e}")
    raise


# --- 参数模型定义 ---
class MCPSearchHotelsParams(BaseModel):
    location: Optional[str] = Field(None, description="酒店所在城市或区域")
    price_tier: Optional[str] = Field(None, description="价格等级 (经济, 中等, 高档, 豪华)")
    min_rating: Optional[float] = Field(None, ge=0.0, le=5.0, description="最低评分 (0-5)")


class MCPGetHotelDetailsParams(BaseModel):
    hotel_id: int = Field(..., gt=0, description="酒店唯一标识符")


class MCPGetAvailableRoomsParams(BaseModel):
    hotel_id: int = Field(..., gt=0, description="酒店唯一标识符")


class MCPCreateBookingParams(BaseModel):
    hotel_id: int = Field(..., gt=0, description="酒店ID")
    guest_name: str = Field(..., description="客人姓名")
    checkin_date: date = Field(..., description="入住日期 (YYYY-MM-DD)")
    checkout_date: date = Field(..., description="退房日期 (YYYY-MM-DD)")
    room_count: int = Field(1, ge=1, description="房间数量")


class MCPCancelBookingParams(BaseModel):
    booking_id: int = Field(..., gt=0, description="预订ID")


class MCPGetBookingDetailsParams(BaseModel):
    booking_id: int = Field(..., gt=0, description="预订ID")


# --- 工具注册 ---
@mcp.tool(
    name="search_hotels",
    description="根据位置、价格等级和评分搜索酒店",
)
async def search_hotels(
        location: Optional[str] = None,
        price_tier: Optional[str] = None,
        min_rating: Optional[float] = None
) -> List[Dict[str, Any]]:
    """根据位置、价格等级和评分搜索酒店"""
    if not hotel_tools:
        raise RuntimeError("酒店工具未初始化")

    logger.info(f"🔍 搜索酒店: location={location}, price_tier={price_tier}, min_rating={min_rating}")

    params = HotelSearchParams(
        location=location,
        price_tier=price_tier,
        min_rating=min_rating
    )

    return await hotel_tools.search_hotels(params)


@mcp.tool(
    name="get_hotel_details",
    description="获取特定酒店的详细信息",
)
async def get_hotel_details(hotel_id: int) -> Dict[str, Any]:
    """获取特定酒店的详细信息"""
    if not hotel_tools:
        raise RuntimeError("酒店工具未初始化")

    logger.info(f"🏨 获取酒店详情: hotel_id={hotel_id}")
    return await hotel_tools.get_hotel_details(hotel_id)


@mcp.tool(
    name="get_available_rooms",
    description="获取指定酒店的可用房间数量",
)
async def get_available_rooms(hotel_id: int) -> int:
    """获取指定酒店的可用房间数量"""
    if not hotel_tools:
        raise RuntimeError("酒店工具未初始化")

    logger.info(f"🛏️ 获取可用房间: hotel_id={hotel_id}")
    return await hotel_tools.get_available_rooms(hotel_id)


@mcp.tool(
    name="create_booking",
    description="创建新的酒店预订",
)
async def create_booking(
        hotel_id: int,
        guest_name: str,
        checkin_date: date,
        checkout_date: date,
        room_count: int = 1
) -> Dict[str, Any]:
    """创建新的酒店预订"""
    if not booking_tools:
        raise RuntimeError("预订工具未初始化")

    logger.info(f"📝 创建预订: hotel_id={hotel_id}, guest={guest_name}")

    params = BookingParams(
        hotel_id=hotel_id,
        guest_name=guest_name,
        checkin_date=checkin_date.isoformat(),
        checkout_date=checkout_date.isoformat(),
        room_count=room_count
    )

    return await booking_tools.create_booking(params)


@mcp.tool(
    name="cancel_booking",
    description="取消现有的酒店预订",
)
async def cancel_booking(booking_id: int) -> Dict[str, Any]:
    """取消现有的酒店预订"""
    if not booking_tools:
        raise RuntimeError("预订工具未初始化")

    logger.info(f"🚫 取消预订: booking_id={booking_id}")
    params = CancellationParams(booking_id=booking_id)
    return await booking_tools.cancel_booking(params)


@mcp.tool(
    name="get_booking_details",
    description="获取预订的详细信息",
)
async def get_booking_details(booking_id: int) -> Dict[str, Any]:
    """获取预订的详细信息"""
    if not booking_tools:
        raise RuntimeError("预订工具未初始化")

    logger.info(f"📄 获取预订详情: booking_id={booking_id}")
    return await booking_tools.get_booking_details(booking_id)


async def debug_list_tools(mcp: FastMCP):
    """调试方法：打印所有工具信息"""
    tools = await mcp.list_tools()
    print("注册的工具:")
    print(tools)
    return tools

# --- 主程序入口 ---
if __name__ == "__main__":
    print("=" * 60)
    print("🏨 酒店管理 MCP 服务器 (FastMCP 版本)")
    print("-" * 60)

    # 在运行前打印工具信息
    import asyncio
    asyncio.run(debug_list_tools(mcp))

    # 使用 FastMCP 的内置运行方法
    mcp.run(transport="streamable-http")
